package com.me.chat.controller.suport;

import com.alibaba.fastjson.JSON;
import com.me.chat.pojo.suport.qo.LoginQO;
import com.me.chat.pojo.suport.ResultBean;
import com.me.chat.service.user.UserService;
import com.me.chat.util.stauts.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

/**
 * @Authhor: qiu
 * @Date: 2021/1/16 2:35 下午
 * @Des: 用于权限相关对接口
 */

@RestController
@RequestMapping("/authority")
public class AuthorityController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    UserService userService;


    //项目服务端口
    @Value("${server.port}")
    private String serverPort;


    /**
     * 登陆
     * @param loginQO
     * @return
     */
    @PostMapping("/login")
    public ResultBean<OAuth2AccessToken> login(@RequestBody LoginQO loginQO){


        //定义默认的错误
        String errorDes = "未知异常";
        //登录url
        final String loginUrl = "http://127.0.0.1:"+serverPort+"/oauth/token";

        MultiValueMap<String,Object> paramMap = new LinkedMultiValueMap<>();

        paramMap.add("grant_type","password");
        paramMap.add("client_id","c1");
        paramMap.add("client_secret","123");
        paramMap.add("username",loginQO.getUsername());
        paramMap.add("password",loginQO.getPassword());

        ResponseEntity<OAuth2AccessToken> responseEntity = null;
        //执行http调用
        try {
            responseEntity = restTemplate.postForEntity(loginUrl,paramMap,OAuth2AccessToken.class);
        }catch (HttpClientErrorException e){
            //得到错误的请求体
            String resBody = e.getResponseBodyAsString();
            //获得错误描述
            errorDes = (String)JSON.parseObject(resBody).get("error_description");
            e.printStackTrace();
            return new ResultBean(StatusCode.ERROR,null,errorDes);
        }

        OAuth2AccessToken oAuth2AccessToken = responseEntity.getBody();

        return new ResultBean(StatusCode.SUCCEED,oAuth2AccessToken,"登录成功");
    }


}
